package com.zzf.msm.controller;

import com.zzf.commonutils.R;
import com.zzf.commonutils.RandomUtil;
import com.zzf.msm.service.MsmService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/edumsm/msm")
@CrossOrigin
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //发送短信
    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable String phone) {

        String code = redisTemplate.opsForValue().get(phone);

        //从Redis获取验证码
        //如果取到了,直接返回
        if (!StringUtils.isEmpty(code)){
            return R.ok();
        }
        //如果取不到,进行阿里云发送

        //生成验证码
        code = RandomUtil.getFourBitRandom();
        Map<String, Object> param = new HashMap<>();
        param.put("code", code);
        //调用service中发送短信方法
        boolean isSend = msmService.send(param, phone);
        if (isSend) {
            //发送成功,吧发送成功的验证吗放到Redis中
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error().message("短信发送失败");
        }
    }
}
